import { fetch } from 'dva';
import { notification } from 'antd';
import router from 'umi/router';
import { routerRedux } from 'dva';
import { NewsTips } from './utils';
import * as requesturl from "@/services/request-url";

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: errortext,
  });
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};

//token

export async function getToken() {
  let token = undefined;
  const casTokenUrl = `${requesturl.login}/cas/jwt/token.do`;
  await fetch(casTokenUrl, {
    method: 'POST',
    credentials: 'include',
  }).then(res =>
    res.json().then(data => {
      const { returnStatus, returnInfo } = data

      if (returnStatus == 200) {
        const currentTime = new Date().getTime();
        window.tokenLastUpdateTime = currentTime;
        window.epmToken = returnInfo;
        token = returnInfo;
        sessionStorage.setItem("token", token)
      } else if (returnStatus == 401) { // 未登录
        // window.location = `http://172.16.193.25:9009` + returnInfo;
        let a = document.createElement("a")
        a.href = `${requesturl.login}/cas/jwt/login.do`;
        a.click();
      }
    })
  );
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options = {},) {
  const defaultOptions = {
    credentials: 'include',
    headers: {
      'p-user-token': sessionStorage.getItem("token"),
    }
  };
  const newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT' || newOptions.method === 'DELETE') {
    newOptions.headers = {
      Accept: 'application/json;charset=UTF-8',
      //              cacheControl: 'no-cache',
      'Content-Type': 'application/json;charset=UTF-8',
      ...newOptions.headers
    };
    if (!(newOptions.body instanceof FormData) && typeof newOptions.body !== 'string') {

      const { body } = newOptions;
      /* if (body) {
          const params = new URLSearchParams();
          Object.keys(body)
              .forEach((item) => {
                  return params.append(item, body[item]);
              });
          newOptions.body = params;
      } */
      newOptions.body = JSON.stringify(body);
    }
  }
  // if (
  //   newOptions.method === 'POST'
  // ) {
  //   if (typeof newOptions.body === 'string') {
  //     newOptions.headers = {
  //       'Content-Type': 'application/json',
  //       ...newOptions.headers
  //     };
  //   }
  //   if (!(newOptions.body instanceof FormData) && typeof newOptions.body === 'object') {
  //     const { body } = newOptions;
  //     if (body) {
  //       const params = new URLSearchParams();
  //       Object.keys(body)
  //         .forEach((item) => {
  //           return params.append(item, body[item] == null ? '' : body[item]);
  //         });

  //       newOptions.body = params;
  //     }
  //   }
  // }
  const newUrl = url.indexOf('?') > -1 ? `${url}&_dc=${Date.now()}` : `${url}?_dc=${Date.now()}`;

  return fetch(newUrl, newOptions)
    .then(checkStatus)
    .then((response) => {
      if (response.url.indexOf("downloadStandModel?id=") > -1) {
        return response.blob();
      } else {
        return response.json();
      }
    }).then((result) => {
      if ('code' in result && (result.code.toString() === '403' || result.code.toString() === '3')) {
        throw result;
      }
      return result;
    })
    .catch(e => {
      if ('code' in e && (e.code.toString() === '403' || e.code.toString() === '3')) {
        /* eslint-disable no-underscore-dangle */
        console.log("1111111111111111111111")
        getToken()

        NewsTips(e.msg);
        localStorage.removeItem('menuAuthByUserId');
        localStorage.removeItem('personInfo');
        localStorage.removeItem('tokenId');
        localStorage.removeItem('userType');
        localStorage.removeItem('userId');
        localStorage.removeItem('antd-pro-authority');
        window.g_app._store.dispatch(routerRedux.push('/login'));
        return e;
      } else if ('code' in e && e.code.toString() === '5') {
        notification.warn(e.msg || '证书过期');
        window.g_app._store.dispatch({
          type: 'global/logout',
          payload: {
            tokenId: sessionStorage.getItem('tokenId')
          }
        });
      } else {
        const status = e.status || e.name;
        if (status === 401) {
          // @HACK
          /* eslint-disable no-underscore-dangle */
          window.g_app._store.dispatch({
            type: 'global/logout',
            payload: {
              tokenId: sessionStorage.getItem('tokenId')
            }
          });
          return;
        }
        // environment should not be used
        if (status === 403) {
          router.push('/403');
          return;
        }
        if (status <= 504 && status >= 500) {
          //router.push('/exception/500');
          return;
        }
        if (status >= 404 && status < 422) {
          router.push('/404');
        }
      }
    });
}
